const INFO_URL      = 'http://your_server_ip:5050/userpage/info';
const SEND_PIC_URL  = 'http://your_server_ip:4000/userpage/sendpic';
// 后端主机和端口
const SERVER_ORIGIN = 'http://your_server_ip:5050';

function formatDateFromIso(isoString) {
  const [datePart] = isoString.split('T');
  const [year, month, day] = datePart.split('-');
  return `${year}年${parseInt(month, 10)}月${parseInt(day, 10)}日`;
}

function formatDateForVoteTime(isoString) {
  const [year, month, day] = isoString.split('/');
  console.log(`投票时间：${year}年${month}月${day}日`);
  return `${year}年${parseInt(month, 10)}月${parseInt(day, 10)}日`;
}

function diffDaysFromNow(chineseDateStr) {
  const match = chineseDateStr.match(/^(\d{4})年(\d{1,2})月(\d{1,2})日$/);
  if (!match) throw new Error('日期格式应为 YYYY年MM月DD日');
  const [, y, m, d] = match.map((v, i) => i>0 ? parseInt(v,10) : v);
  const target = new Date(y, m-1, d);
  const today  = new Date();
  today.setHours(0,0,0,0);
  const msPerDay = 1000*60*60*24;
  return Math.round(Math.abs((today - target) / msPerDay));
}

fetch(INFO_URL, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ currentTime: new Date().toISOString().slice(0,10), ip: '' })
})
  .then(res => res.json())
  .then(data => {
    // 渲染基本信息
    document.getElementById('username').textContent    = data.username;
    document.getElementById('createdText').textContent = formatDateFromIso(data.createdTime);

    // 最后一次投票
    if (!data.vote_time) {
      document.getElementById('lastVote').textContent = '未投票';
    } else {
      document.getElementById('lastVote').textContent = formatDateForVoteTime(data.vote_time);
    }

    document.getElementById('remainingVotes').textContent = data.vote_num;
    document.getElementById('gameDays').textContent      = diffDaysFromNow(formatDateFromIso(data.createdTime)) + ' 天';

    // 渲染角色区块，数据来自 data.extra
    const container = document.getElementById('characterNum');
    if (data.characterNum === 0) {
      const article = document.createElement('article');
      article.className = 'col-6 col-12-xsmall work-item';
      article.innerHTML = `<h3>您还未上传自创角色</h3>`;
      container.appendChild(article);
    } else {
      for (let i = 1; i <= data.characterNum; i++) {
        const nameKey = 'name_' + i;
        const voteKey = 'currentVotes_' + i;
        const article = document.createElement('article');
        article.className = 'col-6 col-12-xsmall work-item';
        article.innerHTML = `
          <h3>角色名：${data.extra[nameKey]}</h3>
          <p>当前票数：${data.extra[voteKey]}</p><br/>
        `;
        container.appendChild(article);
      }
    }

    // —— 关键改动：用 picUrl 字段，并拼接 SERVER_ORIGIN —— 
    return fetch(SERVER_ORIGIN + data.picUrl);
  })
  .then(res => res.blob())
  .then(blob => {
    document.getElementById('avatarImg').src = URL.createObjectURL(blob);
  })
  .catch(console.error);

function handleUpload(type) {
  const username = document.getElementById('username').textContent;
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.style.display = 'none';
  document.body.appendChild(input);

  input.onchange = () => {
    const file = input.files[0];
    if (!file) { document.body.removeChild(input); return; }
    if (file.size > 4 * 1024 * 1024) { alert('图片过大，需小于4MB'); document.body.removeChild(input); return; }

    const baseName = prompt('请输入图片名称（不含后缀）：');
    if (!baseName) { alert('须输入图片名称'); document.body.removeChild(input); return; }

    // 重命名文件
    const ext = file.name.slice(file.name.lastIndexOf('.'));
    const renamedFile = new File([file], baseName + ext, { type: file.type });

    // 构建 FormData：二进制流 + metadata
    const form = new FormData();
    form.append('file', renamedFile); // 图片文件

    // 将 metadata 作为字符串形式传递，符合后端要求的 JSON 格式
    const metadata = JSON.stringify({
      imageClass: type,   // 图片分类（如 "user" 或 "character"）
      imageName: baseName // 图片名称
    });
    form.append('metadata', metadata); // 添加metadata字段

    // 发送请求到后端
    fetch(SEND_PIC_URL, { method: 'POST', body: form })
      .then(res => {
        console.log('Response Status:', res.status); // 输出返回的状态码
        return res.json(); // 解析响应的JSON
      })
      .then(json => {
        console.log('Response JSON:', json); // 输出返回的JSON内容

        if (json && json.msg) {  // 检查返回的JSON是否包含msg字段
          alert(json.msg); // 提示返回的消息
          document.getElementById('uploadMsg').textContent = json.msg || '上传成功';
        } else {
          alert('上传成功');
        }

        if (type === 'user') {
          const imgEl = document.getElementById('avatarImg');
          const url   = URL.createObjectURL(renamedFile);
          imgEl.src  = url;
          imgEl.onload = () => URL.revokeObjectURL(url);
        }
      })
      .catch(error => {
        // 捕获网络或其他错误
        alert('上传失败！请重新尝试上传角色形象');
        console.error('Error:', error);  // 输出详细的错误信息
      })
      .finally(() => {
        document.body.removeChild(input); // 无论如何移除input元素
      });
  };

  input.click();
}

// 绑定上传事件，分别处理用户头像和角色图片
document.getElementById('uploadAvatarBtn')
  .addEventListener('click', () => handleUpload('user'));
document.getElementById('uploadCharacterBtn')
  .addEventListener('click', () => handleUpload('character'));
